# -*- coding: utf-8 -*-
# @Time    : 2021/8/11 9:02
# @Author  : Flora.Chen
# @File    : login_api.py
# @Software: PyCharm
# @Desc: 登录接口

from common.baseapi import BaseApi
from loguru import logger


class TrustieLogin(BaseApi):
    """trustie登录"""

    def __init__(self, host):
        super().__init__()
        self.host = host

    def get_token_session_api(self):
        """获取cookie"""
        response = self.send_request(url=self.host, method="GET", verify=False)
        return response.cookies

    def login_api(self, user, pwd):
        """登录"""
        headers = {"Content-Type": "application/json;charset=UTF-8"}

        data = {"login": user, "password": pwd,
                "autologin": 1}
        cookies = self.get_token_session_api()
        response = self.send_request(url=self.host + "/api/accounts/login.json", method="POST", headers=headers,
                                     json=data,
                                     cookies=cookies,
                                     allow_redirects=False)
        try:
            json_data = response.json()
            if json_data["login"] == user:
                logger.debug(f'登录接口请求成功！user_id={json_data["user_id"]}')
                return response
        except Exception as e:
            logger.error(f"登录接口请求错误：{e}")


